package thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-05-23
 * Time: 22:48
 */
class Counter {
    private static int count = 0;

    public void add1() {
        synchronized (this) {
            count++;
        }
    }

    //使用synchronized修饰方法 相当于针对this进行加锁(变形)
   synchronized public void add2() {
        count++;
    }

    //静态方法 相当于针对类对象加锁
    synchronized public static void add3() {
        count++;//count要变被static修饰
    }


    public static void add4() {
        //            拿到类对象
        synchronized (Counter.class) {
            count++;
        }
    }

    public int getCount() {
        return count;
    }
}
public class Demo18 {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();

        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                c.add1();
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                c.add1();
            }
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        System.out.println("count: " + c.getCount());

    }
}
